<script setup lang="ts">
import { ref, onMounted, computed, watch, onUnmounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import { getExamInfoForUserApi, saveExamAnswerResultForUserApi, getExamPaperQuestionForUserApi } from '#/api/manage/examination-mgr';
import type { ExamInfo } from '#/api/manage/type';
import type { QuestionItem, QuestionSection } from '#/types/question';
import Card from './card.vue';
import Question from './question.vue';
import { getTypeName, RADIO, CHECKBOX, TRUE_FALSE, FILL_BLANK, ESSAY } from '#/views/manage/modules/const';
import { ElMessage } from 'element-plus';
import { QUESTION_STATUS } from '../const';
import { cloneDeep } from '@vben/utils';
import { $t } from '@vben/locales';

const route = useRoute();
const router = useRouter();
const examInfo = ref<ExamInfo>();
const cardSections = ref<QuestionSection[]>([]);
const isExamTerminated = ref(false);
const loading = ref(false);

// 转换接口数据为cardSections格式
const convertToCardSections = (questionList: any[]) => {
  const sections: QuestionSection[] = [];
  let sectionIndex = 1;

  questionList.forEach((questionGroup) => {
    Object.keys(questionGroup).forEach((questionType) => {
      const questions = questionGroup[questionType];
      if (questions && questions.length > 0) {
        // 计算总分数
        const totalScore = questions.reduce((sum: number, q: any) => sum + parseInt(q.score || 0), 0);

        // 转换题目格式
        const questionItems: QuestionItem[] = questions.map((q: any, index: number) => {
          // 解析options为对象
          let parsedOptions = null;
          if (q.options) {
            try {
              parsedOptions = typeof q.options === 'string' ? JSON.parse(q.options) : q.options;
            } catch (e) {
              console.warn('Failed to parse options:', q.options);
              parsedOptions = q.options;
            }
          }

          let status = null, answer = q.type === ESSAY ? q.answer : JSON.parse(q.answer as string);
          if (q.type === RADIO || q.type === CHECKBOX) {
            status = answer?.length ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED;
          }

          if (q.type === TRUE_FALSE) {
            status = answer?.id > 0 ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED;
          }
          if (q.type === FILL_BLANK) {
            status = answer.some((item: any) => !!item) ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED;
          }
          if (q.type === ESSAY) {
            status = answer?.trim() ? QUESTION_STATUS.ANSWERED : QUESTION_STATUS.UNANSWERED;
          }

          return {
            id: q.id,
            answer,
            index: index + 1,
            markDoubtful: q.markDoubtful,
            status: q.markDoubtful ? QUESTION_STATUS.MARKED : status,
            originalData: {
              ...q,
              options: parsedOptions
            }
          };
        });

        // 生成章节标题
        const sectionNumbers = ["一", "二", "三", "四", "五", "六", "七", "八", "九", "十"];
        const sectionNumber = sectionNumbers[sectionIndex - 1] || sectionIndex;
        const typeName = getTypeName(questionType)?.label || questionType;
        sections.push({
          title: $t('examCore.sectionTitleFormat', { number: sectionNumber, typeName }),
          description: $t('examCore.questions.questionSummary', { count: questions.length, score: totalScore }),
          questions: questionItems,
          type: questionType
        });

        sectionIndex++;
      }
    });
  });

  return sections;
};

// 获取考试ID
watch(() => route.params.id, (examId) => {
  if (examId) {
    loading.value = true;
    getExamPaperQuestionForUserApi(examId as string).then(res => {
      examInfo.value = res;
      // 转换题目数据为cardSections格式
      if (res.questionList && res.questionList.length > 0) {
        cardSections.value = convertToCardSections(res.questionList);
      }
    }).finally(() => {
      loading.value = false;
    });
  }
}, { immediate: true });

// 处理题目点击事件
const handleQuestionClick = (question: QuestionItem) => {
  // 如果考试已终止，不允许点击
  if (isExamTerminated.value) {
    return;
  }
  // 滚动到对应题目
  const questionElement = document.querySelector(`[data-question-id="${question.id}"]`);
  if (questionElement) {
    questionElement.scrollIntoView({ behavior: 'smooth', block: 'start' });
  }
};

// 处理考试终止状态变化
const handleExamTerminated = (terminated: boolean) => {
  isExamTerminated.value = terminated;
};

// 处理提交试卷事件
const handleSubmit = (submit: boolean = false, isTerminated?: boolean) => {
  console.log('提交试卷', cardSections);
  // 收集所有已答题目的答案
  const collectAnswers = () => {
    const answers: Record<string | number, any> = {};
    const answerList = cloneDeep(cardSections.value);
    answerList.forEach(section => {
      section.questions.forEach(question => {
        answers[question.id] = typeof question.answer !== 'string' ? JSON.stringify(question.answer) : question.answer;
      });
    });
    return answers;
  };
  // 收集所有答案
  const allAnswers = collectAnswers();
  console.log('收集到的答案:', allAnswers);
  // 调用提交API
  saveExamAnswerResultForUserApi({
    examScoreId: route.params.id,
    questionAnswerMap: allAnswers,
    submit
  }).then(res => {
    console.log('提交结果:', res);
    if (submit && isTerminated) {
      ElMessage.success($t('common.successTxt'));
      router.push({
        path: `/accreditExam/explainCore/${route.query.examId}`
      });
    }
  });
};

</script>

<template>
  <div class="exam-start w-full h-full flex flex-col bg-[#f5f6fa] items-center py-4" v-loading="loading">
    <div class="w-full flex-1 max-w-[1200px] bg-white rounded-lg shadow-sm flex flex-col">
      <div class="flex items-center justify-between px-6 font-medium text-xl h-12 leading-12 flex-shrink-0">{{
        examInfo?.name }}</div>
      <hr class="border-t border-gray-200 flex-shrink-0" />
      <div class="px-6 pb-8 pt-4" style="height: calc(100vh - 150px);">
        <div class="flex h-full">
          <div class="flex-1 mr-4 question-scroll-wrapper">
            <Question :question="cardSections" @submit="handleSubmit" />
          </div>
          <div class="w-[330px] sticky-card">
            <Card class="h-full" :sections="cardSections" @question-click="handleQuestionClick" @submit="handleSubmit"
              @exam-terminated="handleExamTerminated" />
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<style scoped>
/* 题目滚动区域 */
.question-scroll-wrapper {
  height: 100%;
  overflow-y: auto;
  overflow-x: hidden;
  padding-right: 8px;
}

/* 自定义滚动条样式 */
.question-scroll-wrapper::-webkit-scrollbar {
  width: 6px;
}

.question-scroll-wrapper::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 3px;
}

.question-scroll-wrapper::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 3px;
}

.question-scroll-wrapper::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}

/* 答题卡sticky定位样式 */
.sticky-card {
  position: sticky;
  top: 20px;
  height: calc(100vh - 180px);
  max-height: calc(100vh - 160px);
  width: 330px;
  background: #f2f7fd;
  border-radius: 8px;
  overflow: hidden;
}
</style>
